class Comment < ActiveRecord::Base
  belongs_to :user  
  belongs_to :topic
  
  default_value_for :vote, 0
  
  before_validation_on_create :elaborate
  
  def elaborate      
    require 'open-uri'
    require 'json'            
    self.message = self.message.gsub(/http[s]?:\/\/[^\s]+/) do |m|      
      replace_url(m)
    end
    self.message = self.message.gsub(/\n/, '<br />')
    
  end
  
  private  

  def replace_url(i)    
    if (i =~ URI::regexp).nil?
        return i
    else         
        begin               
          url = 'http://oohembed.com/oohembed/?url=' + i.sub("http://", "http%3A//").sub("\n","")    
          buffer = open(url, "UserAgent" => "Ruby-Wget").read        
          result = JSON.parse(buffer)
          
          thumb = Thumb.create(
           :user_id => self.user_id,
           :provider_name => result['provider_name'],
           :kind => result['type'],
           :url => result['url'],
           :html => result['html'],
           :title => result['title'],
           :thumbnail_url => result['thumbnail_url']           
          )
          
          i = " <a href='#'><div class='comment_thumb_div link_gray_ani'><img class='comment_thumb_img' src='#{ thumb.thumbnail_url || Tumbnail.icon(thumb.provider_name) }' />" +
            "<div class='comment_thumb_title'><p>#{ thumb.title.to_s unless thumb.title.blank? }</p>" + 
            "<p class='comment_thumb_provider'> #{ thumb.provider_name.to_s }</p></div><div class='separator'><span></span></div></div></a>"          
        rescue
            if ([".jpg", ".jpeg", ".png", ".gif"].include?(File.extname(i)))
                i = " <img src='#{i}' alt='' />"              
            else
                i = " <a href='#{i}'>#{i}</a>"
            end            
        end
        return i
     end
  end

end
